package com.admin.utils;


import com.admin.business.background.venusOaSmsadminInfo.VenusOaSmsadminInfoDao;
import com.admin.utils.constants.CommonConstants;
import com.tiangong.framework.bo.CDO;
import com.zmbsms.os.core.util.StringUtils;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MobileSendUtil {

	@Reference
	private RedisUtilKey redisTemplate;

	VenusOaSmsadminInfoDao venusOaSmsadminInfoDao;



	public  void main(String[] args) {
	    try {
			MobileSendUtil mobileSendUtil=new MobileSendUtil();
			mobileSendUtil.sendMessage("13511032990","newLegalMessage",1,"幸虎");
        }catch (Exception e){
			e.printStackTrace();
        }
	}

	/**
	 * 发送短信 mobile手机号  code验证码  type短信类型   minute分钟  content自定义发送内容
	 * 类型
	 * @param mobiles
	 * @param type
	 * @return
	 */
	public Map<String,String> sendMessage(String mobiles, String type, int minute, String contents){
		String userCode="BJCLHYCF";//账号
		String 	messageUserPass="f_@O3592@p";//密码
		String 	messageUserKeyword="\u52A9\u4E1A\u5E73\u53F0";//Keyword
		String code= RandomStrUtil.getRandInt(4);
		Map<String,String> resultMap=new HashMap<>();
		resultMap.put("resCode","fail");
		resultMap.put("msg", "短信发送失败，请稍后再试");

  		String text=contents;
		switch (type) {
			case "addUser":
				contents = text;
				break;
			case "leSendPassWord":
				contents = "您的员工"+text+"正在帮你以法人身份注册助业平台物业账号，验证码："+code+"，有效期5分钟，如不是本人同意请忽略该短信!";
				break;
			case "login":
				contents = "您的登录验证码："+code+"，有效期"+minute+"分钟,请妥善保管，不要告诉其他人";
				break;
			case "cashOut":
				contents = "验证码为"+code+"，用于商户平台安全验证，"+minute+"分钟内有效。若非本人操作，请忽略此消息。";
				break;
			case "register":
				contents = "您的注册验证码："+code+"，有效期"+minute+"分钟,请妥善保管，不要告诉其他人";
				break;
			case "forget":
				contents = "您的找回密码验证码："+code+"，有效期"+minute+"分钟，请妥善保管，不要告诉其他人";
				break;
			case "updatePassword":
				contents = "您的修改密码验证码为："+code+"，有效期"+minute+"分钟，请妥善保管，不要告诉其他人";
				break;
			case "newLegalMessage"://短信通知法人（法人新注册）
				contents =text+"帮您注册成为助业平台会员，账号为您的手机号码："+mobiles
						+"密码："+ "wy123456"+"，待企业申请通过就可使用物业管理系统，为了您的账户安全请及时到《助业网》修改您的密码！";
				break;
			case "legalMessage"://短信通知法人（法人已注册）
				text=contents;
				contents = text+"正在帮你申请助业平台物业账户，申请通过就可使用物业系统";
				break;
			case "forUserInviteCode":
				String []str=contents.split(",");
				code=str[3];
				contents = str[0]+"您好，您加入"+str[1]+"的邀请码为:"+str[3]+"，请您在"+minute+"分钟内完成入职申请！";
				break;
			case "checkCompany":
				if(contents.equals("true")){
					contents = "恭喜您，您申请使用《助业物业管理系统》企业认证信息已通过、请登录https://www.515f.com完善信息后，开始使用吧！";//企业审核成功
				}else {
					contents = "对不起，您申请使用《助业物业管理系统》企业认证信息审核失败、请核对信息是否正确重新到https://www.515f.com重新提交！";
				}
				break;
			case "updActivity":
				contents = text;
				break;
			case "smsadmin":
				contents = text;
				break;
			case "reflect":
				contents = text;
				break;
			case "meetSms":
				contents = text;
				break;
			case "updSysUserTel":
				contents ="您正在更换手机号，验证码" + code + "。请勿提供给他人";
				break;
			case "updInvitationCode":
				contents ="您正在修改邀请码，验证码" + code + "。请勿提供给他人";
				break;
			default:
				break;

		}
		try {
			//设置超时时间-可自行调整
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");
			//调用地址
			String url="http://120.55.197.77:1210/Services/MsgSend.asmx/SendMsg";
			//传值
			String getparam="userCode="+ userCode+"&userPass="+ messageUserPass +"&DesNo="+mobiles+
					"&Msg="+contents+"【"+ URLDecoder.decode(messageUserKeyword,"utf8")+"】&Channel=0";
			System.out.println("发送参数："+getparam);
			//接收返回值
			String result=httpGet(url,getparam);
			System.out.println(result);
			//返回值为xml   截取xml中返回的值  进行判断是否成功
			result=result.substring(0,result.lastIndexOf("</string>"));
			result=result.substring(result.lastIndexOf(">")+1);
			Long intResult= Long.parseLong(result);
			if (intResult<0){
				System.out.println("发送失败，失败状态码:"+intResult);
			}else{
				if (!type.equals("forUserInviteCode")){
					redisTemplate.set(CommonConstants.MOBILE_CODE_TIME + mobiles, code, 60L);
					redisTemplate.set(CommonConstants.MOBILE_CODE + mobiles, code, 300L);
					//cacheChannel.setSecond(CommonConstants.MOBILE_CODE_TIME + ":" + mobiles, code, 1);
					//cacheChannel.setSecond(CommonConstants.MOBILE_CODE + ":" + mobiles, code, 5);
				}else {
					//cacheChannel.evict(CommonConstants.MOBILE_CODE + ":" + mobiles);
					redisTemplate.del(CommonConstants.MOBILE_CODE  + mobiles);
					Long min=minute*60L;
					//cacheChannel.setSecond(CommonConstants.MOBILE_CODE_TIME + ":" + mobiles, code, min);
					//cacheChannel.setSecond(CommonConstants.MOBILE_CODE + ":" + mobiles, code, min);
					redisTemplate.set(CommonConstants.MOBILE_CODE_TIME + mobiles, code, min);
					redisTemplate.set(CommonConstants.MOBILE_CODE + mobiles, code, min);
				}
				System.out.println("code++++++++++++++++++++" + code);
				resultMap.put("resCode","success");
				resultMap.put("code",code);
				resultMap.put("msg", "短信发送成功");
				System.out.println("发送成功："+intResult);
				//发送成功，减少短信数量
				int contentsLength = contents.length();
				CDO update =new CDO();
				update.set("id",1);
				String sms_total="1";
				if(contentsLength>70){
					double b=67;
					Double v =contentsLength / b;
					sms_total = v.toString().substring(0, 1);//最多就500字符，7条短信
				}else{
					sms_total="1";
				}
				update.set("sms_total_decrease",sms_total);
				venusOaSmsadminInfoDao.updateVenusOaSmsadminTotal(update);//修改本科技公司的剩余短信条数，如果是后台物业公司发的，还需在VenusOaSmsadminServiceImpl修改物业公司的剩余短信条数
			}
			resultMap.put("intResult",intResult+"");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * @Author Zwl
	 * @Description //TODO 个别使用营销短信通道
	 * @Date 2023-5-23 16:28:34
	 * @Param mobiles
	 type
	 minute
	 contents
	 * @return java.util.Map<java.lang.String,java.lang.String>
	 */
	public  Map<String,String> marketingSMS(String mobiles,String contents){
		String userCode="BJCLHYCF";//账号
		String 	messageUserPass="f_@O3592@p";//密码
		String 	messageUserKeyword="\u52A9\u4E1A\u5E73\u53F0";//Keyword
		String code= RandomStrUtil.getRandInt(4);
		Map<String,String> resultMap=new HashMap<>();
		resultMap.put("resCode","fail");
		resultMap.put("msg", "短信发送失败，请稍后再试");

		if (StringUtils.isEmpty(contents)){
			resultMap.put("msg", "短信发送失败，短信内容不可为空");
			return resultMap;
		}

		try {
			//设置超时时间-可自行调整
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");
			//调用地址
			String url="http://118.178.116.15/winnerrxd/api/mass/SendMsg";
			//传值
			String getparam="userCode="+ userCode+"&userPass="+ messageUserPass +"&DesNo="+mobiles+"&smsType="+"103"+
					"&Msg="+contents+"【"+ URLDecoder.decode(messageUserKeyword,"utf8")+"】&Channel=0";
			System.out.println("发送参数："+getparam);
			//接收返回值
			String result=httpGet(url,getparam);
			System.out.println(result);
			//返回值为xml   截取xml中返回的值  进行判断是否成功
			result=result.substring(0,result.lastIndexOf("</string>"));
			result=result.substring(result.lastIndexOf(">")+1);
			Long intResult= Long.parseLong(result);
			if (intResult<0){
				System.out.println("发送失败，失败状态码:"+intResult);
			}else{
				System.out.println("code++++++++++++++++++++" + code);
				resultMap.put("resCode","success");
				resultMap.put("code",code);
				resultMap.put("msg", "短信发送成功");
				System.out.println("发送成功："+intResult);
				//发送成功，减少短信数量
				int contentsLength = contents.length();
				CDO update =new CDO();
				update.set("id",1);
				int sms_total = 1;
				if (contentsLength > 70) {
					int b = 67;
					sms_total = contentsLength / b;
					if (contentsLength % b != 0) {
						sms_total = sms_total + 1;
					}
				}
				update.set("sms_total_decrease",sms_total);
				venusOaSmsadminInfoDao.updateVenusOaSmsadminTotal(update);//修改本科技公司的剩余短信条数，如果是后台物业公司发的，还需在VenusOaSmsadminServiceImpl修改物业公司的剩余短信条数
			}
			resultMap.put("intResult",intResult+"");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}



	protected static String strToHash(String str) throws NoSuchAlgorithmException {
		MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
		byte[] inputByteArray = str.getBytes();
		messageDigest.update(inputByteArray);
		byte[] resultByteArray = messageDigest.digest();
		return byteArrayToHex(resultByteArray);
	}

	public static String byteArrayToHex(byte[] byteArray) {
		char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
		char[] resultCharArray = new char[byteArray.length * 2];
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		return new String(resultCharArray);
	}


	public static String httpGet(String url,String params){
		String result="";
		try{
			HttpClient client=new DefaultHttpClient();
			if(params!=""){
				url=url+"?"+params;
				System.out.println(url);
			}
			HttpGet httpget=new HttpGet(url);
			HttpResponse response=client.execute(httpget);

			HttpEntity entity=response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				result = convertStreamToString(instreams);
				System.out.println(result);
			}
		}catch(Exception e){}
		return result;
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line =reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}


}


